<template>
  <div>
    <!-- 面包屑导航 -->
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <el-button type="primary">添加角色</el-button>
      </el-row>
      <!-- 角色列表区 -->
      <el-table :data="roleList" stripe border>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <!-- 在展开列中创建新行,表示展开列打开的新行 -->
          <template slot-scope="scope">
            <!-- 展开的区域可以创建多行,每行表示一个角色 -->
            <el-row
              :class="['bgBottom', 'vcenter', index == 0 ? 'bgTop' : '']"
              v-for="(item, index) in scope.row.children"
              :key="item.id"
            >
              <!--渲染第一列的一级权限名称 -->
              <el-col :span="5">
                <el-tag
                  type="primary"
                  closable
                  @close="removeRightById(scope.row, item.id)"
                >
                  {{ item.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级权限 -->
              <el-col :span="19">
                <!-- 二级权限的每个权限占一行 -->
                <el-row
                  :class="[index2 == 0 ? '' : 'bgTop', 'vcenter']"
                  v-for="(item2, index2) in item.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item3, index3) in item2.children"
                      :key="index3.id"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="序号" type="index" width="60"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="small"
              >编辑</el-button
            >
            <el-button type="danger" icon="el-icon-delete" size="small"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="small"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClosed"
    >
      <!-- 树形组件
    show-checkbox:显示复选框
    node-key:设置选中节点对应的值
    default-expand-all:是否默认展开所有节点
    :default-checked-keys 设置默认选中项的数组
    ref:设置引用 -->
      <el-tree
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.getRolesList()
  },
  data() {
    return {
      // 角色列表
      roleList: [],
      // 显示分配权限对话框
      setRightDialogVisible: false,
      // 保存权限列表
      rightsList: [],
      // 树形控件的绑定属性
      treeProps: {
        label: 'authName',
        children: 'children',
      },
      //设置树形控件中默认选中的内容
      defKeys: [],
      //角色id
      roleId: '',
    }
  },
  methods: {
    // 获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status != 200)
        return this.$message.error('获取角色列表失败:' + res.meta.msg)
      // console.log(res);
      this.roleList = res.data
    },

    // 移除权限
    async removeRightById(role, rightId) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      //如果用户点击确认，则confirmResult 为'confirm'
      //如果用户点击取消, 则confirmResult获取的就是catch的错误消息'cancel'
      if (confirmResult != 'confirm') {
        return this.$message.info('已经取消删除')
      }
      // console.log("确认了删除:"+roleId);
      // console.log("确认了删除:"+rightId);
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status != 200)
        return this.$$message.error('删除权限失败:' + res.meta.msg)
      this.$message.success('成功删除权限')
      // 返回数据的data是最新的权限,可以送回role.chileren更新显示
      role.children = res.data
    },
    //显示分配权限对话框
    async showSetRightDialog(role) {
      // 在显示分配权限对话框打开的时候,将roleid保存到私有数据中,
      //目的是可以在对话框的确定时候,写入权限需要角色id
      this.roleId = role.id
      // console.log(role);
      //  请求接口数据
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status != 200)
        return this.$message.error('获取权限列表错误:' + res.meta.msg)
      // console.log(res.data)
      this.rightsList = res.data

      //调用getLeafKeys进行递归，将三级权限添加到数组中
      this.getLeafKeys(role, this.defKeys)
      // console.log(this.defKeys);
      this.setRightDialogVisible = true
    },
    // 获取三级权限节点的id
    getLeafKeys(node, arr) {
      //该函数会获取到当前角色的所有三级权限id并添加到defKeys中
      //如果当前节点不包含children属性，则表示node为三级权限
      if (!node.children) {
        return arr.push(node.id)
      }
      //递归调用
      node.children.forEach((item) => this.getLeafKeys(item, arr))
    },
    // 关闭分配权限对话框
    setRightDialogClosed() {
      this.defKeys = []
    },
    //分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ]
      // 拼接为字符串
      const idStr = keys.join(',')
      // 请求api
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, {
        rids: idStr,
      })
      if (res.meta.status != 200)
        return this.$message.error('权限写入错误:' + res.meta.msg)
      this.$message.success('权限写入成功')
      //重新读取并刷新权限
      this.getRolesList()
      //关闭对话框
      this.setRightDialogVisible=false

    },
  },
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 15px;
}
.bgBottom {
  border-bottom: 1px solid #ccc;
}
.bgTop {
  border-top: 1px solid #ccc;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>